<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-7-6
 * Time: 上午9:56
 */
$nowdate=date("Y-m-d H:i:s");
if (!class_exists("go_sql")) {
    include("/var/www/html/new/conf/le.je");
    $le = new go_sql();
    $le->connect();
}
$ac = '16ucom';
$pw = 'c33367701511b4f6020ec61ded352059';
$inSide = new SoapClient(null, array("location" => "http://localhost/open/openService/pft_insideMX.php", "uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));

$xml=<<<MXL
<?xml version="1.0" encoding="UTF-8"?>
<request xmlns="http://piao.qunar.com/2013/QMenpiaoRequestSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoRequestSchemaQMRequestDataSchema-2.0.1.xsd">
    <header>
        <application>Qunar.Menpiao.Agent</application>
        <processor>SupplierDataExchangeProcessor</processor>
        <version>v2.0.1</version>
        <bodyType>CheckCreateOrderForAfterPaySyncRequestBody</bodyType>
        <createUser>multiCategoryTest001</createUser>
        <createTime>2015-09-09 15:09:51</createTime>
        <supplierIdentity>multiCategoryTest001</supplierIdentity>
    </header>
    <body xsi:type="CreateOrderForBeforePaySyncRequestBody">
    <orderInfo>
        <orderId>160536100395000007</orderId>
        <product>
            <resourceId>23357_113</resourceId>
            <productName>（pzp测试）0826短信三教师票</productName>
            <visitDate>2015-09-09</visitDate>
            <sellPrice>200</sellPrice>
            <cashBackMoney>0</cashBackMoney>
        </product>
        <contactPerson>
            <name>崔鹏飞</name>
            <namePinyin/>
            <mobile>18624022420</mobile>
            <email/>
            <address/>
            <zipCode/>
        </contactPerson>
        <visitPerson>
            <person>
                <name>崔鹏飞</name>
                <namePinyin/>
                <credentials/>
                <credentialsType/>
                <defined1Value/>
                <defined2Value/>
            </person>
        </visitPerson>
        <orderQuantity>2</orderQuantity>
        <orderPrice>400</orderPrice>
        <orderCashBackMoney>0</orderCashBackMoney>
        <orderStatus>PREPAY_ORDER_INIT</orderStatus>
        <orderRemark/>
        <orderSource>WWW</orderSource>
        <eticketNo/>
    </orderInfo>
    </body>
</request>
MXL;
$sxml = simplexml_load_string($xml);

$supplierIdentity=(string)$sxml->header->supplierIdentity;
$signkey = 'DEBUGSINGKEY';
$remoteorder = (string)$sxml->body->orderInfo->orderId;//远端订单号
$orderQuantity = (string)$sxml->body->orderInfo->orderQuantity;//订单数量
$orderid = (string)$sxml->body->orderInfo->product->resourceId;//产品id
$visitDate=(string)$sxml->body->orderInfo->product->visitDate;//游玩日期
//    $cashBackMoney = ((int)$sxml->body->orderInfo->product->cashBackMoney);//返回金额
$product = explode("_",$orderid);//门票id和供应商id
$tid = $product['0'];
$aid= $product['1'];
$fid = 2175;//分销商id



if(!$tid)  {
    $code = 101;
    $describe = '请求数据有误';
    exit;
}

$sql= "select pid from uu_jq_ticket where id={$product['0']} limit 1 ";
$GLOBALS['le']->query($sql);
if(!($pid =$GLOBALS['le']->fetch_assoc())){

}else {
    $pid = $GLOBALS['le']->f('pid');
}

// 获取产品数据
$str="select p.id as pid,p.apply_limit,p.salerid,p.p_status,p.apply_did,l.id as lid,l.title as ltitle,l.p_type,t.id as tid,t.tprice,t.pay,t.title as ttitle,t.delaydays,t.ddays,t.buy_limit_low,t.buy_limit_up,t.status,t.storage_open,t.order_start,t.order_end,t.storage,t.getaddr,f.dhour,f.series_model,f.mdays,f.v_ID_support,t.sourceT from uu_products p left join uu_jq_ticket t on p.id=t.pid left join uu_land l on p.contact_id=l.id left join uu_land_f f on p.id=f.pid where p.id=$pid limit 1";
$GLOBALS['le']->query($str);
$p_info=$GLOBALS['le']->fetch_assoc();


// 是否在售
if($p_info['apply_limit']!=1){
    $code = 104;
    $describe = '无权限购买';
    exit;
}

// 是否有购买权限

$auth = authCheck($fid,$aid,$p_info);
if(!$auth['auth']){
    $code = 105;
    $describe = '无权限购买';
    exit;

}

// 检测套票子票
if($p_info['p_type']=='F'){
    $chkResult = \pft\Prod\Sale::PackageTicketCheck($this->s, $pid, $fid, $aid, substr($valid_start,0,10), $num);
    if($chkResult['code']!=200){
        logfile("[$remoteorder]子票出错，出错信息:{$chkResult['msg']},产品ID:$pid");
        $code = 105;
        $describe = '子票出错';
        exit;
    }
}

// 价格获取
$begintime = $visitDate;
$tnum = $orderQuantity;

// 如果是时间段，判断预定日是否在有效期内
if($p_info['p_type']!='F' && $p_info['order_start']!='' && $p_info['order_end']!=''){
    if($p_info['order_end']<$begintime){
        $code = 106;
        $describe = '购买日期门票失效';
        exit;
    }
}

// 获取分销商信息
$sql = "select account,dname from pft_member where id=$fid limit 1";
$GLOBALS['le']->query($sql);
if(!($d_info=$GLOBALS['le']->fetch_assoc()))  {
    $code = 107;
    $describe = '分销商不存在';
    exit;
}

$xml = $inSide->Dynamic_Price_And_Storage($d_info['account'],$pid,substr($begintime,0,10),1,0,1,$aid);

if($xml==105 || $xml==1065){
    $code = 108;
    $describe = '出游时间无价格';
    exit;
}

$obj = simplexml_load_string($xml);

// 库存判断
$storage = $obj->Rec->UUstorage;
if($storage>-1){
    $storagexml = $inSide->Dynamic_Storage_Check($p_info['tid'], 1, substr($begintime,0,10));
    $storagexml = simplexml_load_string($storagexml);
    $dayStorage = explode("|", (string)$storagexml->Rec->UUXstr);
    $useStorage = $dayStorage[1];// 已使用库存
    $surplus    = $storage - $useStorage;// 剩余库存
    if($surplus<$tnum){
        $code = 109;
        $describe= '库存不足';
        exit;
    }
}

// 订单金额
$tprice = (string)$obj->Rec->UUsprice;
$totalMoney = $tprice*$tnum;

$paymodel = 2;// 授信余额
//    print_r($inSide);
//    print_r($fid);
//    print_r($aid);
$fundXml=$inSide->PFT_Member_Fund($fid,1,$aid);
$fundXml1=simplexml_load_string($fundXml);

$fundXml=$inSide->PFT_Member_Fund($fid,2,$aid);
$fundXml2=simplexml_load_string($fundXml);
$canUseMoney = (string)$fundXml1->Rec->UUkmoney + (string)$fundXml2->Rec->UUbasecredit;
if(($canUseMoney)<$totalMoney){
    $code = 111;
    $describe= '余额不足';
    exit;
}else{
    $code = 1000;
    $describe= '成功';
    $string=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<response xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoResponseSchema QMResponseDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<header>
		<application>Qunar.Menpiao.Agent</application>
		<processor>SupplierDataExchangeProcessor</processor>
		<version>v2.0.1</version>
		<bodyType>CheckCreateOrderForAfterPaySyncResponseBody</bodyType>
		<createUser>{$supplierIdentity}</createUser>
		<createTime>{$nowdate}</createTime>
		<code>{$code}</code>
		<describe>{$describe}</describe>
	</header>
	<body xsi:type="CheckCreateOrderForAfterPaySyncResponseBody">
		<message></message>
	</body>
</response>
XML;
    echo  ($string);
    exit;
    $bstr=base64_encode($string);

    $signed=strtoupper(md5($signkey.$bstr));

    $arr=array('data'=>$bstr,'signed'=>$signed,'securityType'=>'MD5');
    echo json_encode($arr);

}












function authCheck($fid,$aid,$p_info){
    $arr = array('self'=>false,'auth'=>false);
    $pid = $p_info['pid'];
    if($p_info['apply_did']==$fid){ // 自供应
        $arr['self'] = true;
        $arr['auth'] = true;
        return $arr;
    }
    if($p_info['apply_did']==$aid){ // 直接供应
        $sql="select pids from `pft_product_sale_list` where fid=$fid and aid=$aid LIMIT 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $pids=$GLOBALS['le']->f("pids");
        if($pids=='A') $arr['auth'] = true;
        if(in_array($pid,explode(",",$pids)))$arr['auth'] = true;
        return $arr;
    }
    // 多手供应
    $sql="select * from pft_p_apply_evolute where pid=$pid and sid=$aid and fid=$fid and status=0 limit 1";
    $GLOBALS['le']->query($sql);
    if($row=$GLOBALS['le']->fetch_assoc())$arr['auth'] = true;
    return $arr;
}


function logfile($txt)
{
    $fp = fopen('test.txt', "a");
    flock($fp, LOCK_EX);
    fwrite($fp, $txt . "\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}
